<template>
  <el-container class="category-page-container">
    <!-- 主要内容区域 -->
    <el-main class="category-main-content">
      <el-card class="category-form-card">
        <template #header>
          <div class="card-header">
            <span>添加分类</span>
          </div>
        </template>

        <el-form :model="categoryForm" :rules="categoryRules" ref="formRef" label-width="100px" class="category-form">
          <!-- 分类基本信息 -->
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="categoryForm.name" placeholder="请输入分类名称" clearable />
          </el-form-item>

          <!-- 表单操作按钮 -->
          <el-form-item class="form-action-buttons">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import request from '@/request';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const formRef = ref(null);

// 分类表单数据
const categoryForm = reactive({
  name: '',
  iconUrl: '',
});

// 表单验证规则
const categoryRules = reactive({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在2-50个字符', trigger: 'blur' }
  ],
});


// 提交表单
const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request.post('users/getcategory/', categoryForm);
        if (response.data.code === 201) {
          ElMessage.success('分类添加成功');
          resetForm();
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  });
};
// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  categoryForm.iconUrl = '';
};
</script>
<style scoped>
.category-page-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.category-main-content {
  padding: 20px;
}

.category-form-card {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.card-header {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.category-form {
  padding: 20px;
}

.form-action-buttons {
  padding-top: 20px;
  display: flex;
  gap: 15px;
}
</style>